package com.baozun.houji.goods.fragment

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.baozhun.mall.common.adapter.CommonGoodsChannelAdapter
import com.baozhun.mall.common.adapter.CommonGoodsSelfAdapter
import com.baozhun.mall.common.base.BaseFragment
import com.baozhun.mall.common.ext.loadListData
import com.baozhun.mall.common.model.bean.ApiPagerResponse
import com.baozhun.mall.common.model.bean.GoodsInfoBean
import com.baozhun.mall.common.model.enums.GoodsSource
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.baozhun.mall.common.util.eventbus.EventMessage
import com.baozhun.mall.common.widget.EmptyView
import com.baozhun.mall.common.widget.customview.filter.CustomFilterDialog
import com.baozun.houji.goods.R
import com.baozun.houji.goods.activity.GoodsDetailActivity
import com.baozun.houji.goods.databinding.FragmentSearchResultBinding
import com.baozun.houji.goods.viewmodel.state.SearchResultViewModel
import com.blankj.utilcode.util.SizeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.listener.OnLoadMoreListener
import com.fondesa.recyclerviewdivider.dividerBuilder
import com.fondesa.recyclerviewdivider.staggeredDividerBuilder
import com.samluys.filtertab.FilterInfoBean
import com.samluys.filtertab.FilterResultBean
import com.samluys.filtertab.FilterTabConfig
import com.samluys.filtertab.listener.OnSelectResultListener
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @Title：搜索结果fragment
 * @Description：
 * @Author：xing.luo
 * @Since：2022/11/09
 * @Version：1.0.0
 */
class SearchResultFragment : BaseFragment<SearchResultViewModel, FragmentSearchResultBinding>(),
    OnItemClickListener, OnSelectResultListener, OnLoadMoreListener, OnRefreshListener {

    private val mProductListAdapter: BaseQuickAdapter<GoodsInfoBean, *>? by lazy {
        if (mGoodsSource == GoodsSource.SELF) CommonGoodsSelfAdapter(
            mViewModel.productList,
            onItemClickListener = this
        ) else CommonGoodsChannelAdapter(mViewModel.productList, onItemClickListener = this)
    }
    private var filterView: CustomFilterDialog? = null
    private var filterParams = hashMapOf<String, String>()
    private val mGoodsSource by lazy { arguments?.getSerializable(SEARCH_TYPE) as GoodsSource }
    private var mKeyword = ""

    companion object {

        private const val SEARCH_TYPE = "searchType"
        private const val INIT_KEYWORDS = "initKeywords"

        fun newInstance(goodsBuyType: GoodsSource, initKeywords: String): SearchResultFragment {
            val args = Bundle()
            val fragment = SearchResultFragment()
            args.putSerializable(SEARCH_TYPE, goodsBuyType)
            args.putString(INIT_KEYWORDS, initKeywords)
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBusUtils.register(this)
        mKeyword = arguments?.getString(INIT_KEYWORDS).toString()
        mDataBinding.baseRefreshLayout.setOnRefreshListener(this)
        mProductListAdapter?.loadMoreModule?.setOnLoadMoreListener(this)
        initFilterView()
        mProductListAdapter?.setEmptyView(
            EmptyView.Builder(mActivity).emptyHintText(com.baozhun.mall.res.R.string.no_search_data_hint)
                .emptyImage(R.drawable.ic_data_empty_search)
                .build()
        )
        if (mGoodsSource == GoodsSource.SELF) {
            mDataBinding.rvSearchProductList.layoutManager = LinearLayoutManager(mActivity)
            mDataBinding?.rvSearchProductList?.addItemDecoration(
                mActivity.dividerBuilder()
                    .size(SizeUtils.dp2px(8f))
                    .color(ContextCompat.getColor(mActivity, com.baozhun.mall.res.R.color.color_F7F7F7))
                    .build()
            )
            if (mDataBinding?.rvSearchProductList?.layoutParams is ViewGroup.MarginLayoutParams) {
                (mDataBinding?.rvSearchProductList?.layoutParams as ViewGroup.MarginLayoutParams).setMargins(SizeUtils.dp2px(8f), SizeUtils.dp2px(8f), SizeUtils.dp2px(8f), 0)
            }
        } else {
            mDataBinding?.rvSearchProductList?.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
            mDataBinding?.rvSearchProductList?.addItemDecoration(
                mActivity.staggeredDividerBuilder()
                    .size(SizeUtils.dp2px(7f))
                    .color(ContextCompat.getColor(mActivity, com.baozhun.mall.res.R.color.color_F7F7F7))
                    .build()
            )
            if (mDataBinding?.rvSearchProductList?.layoutParams is ViewGroup.MarginLayoutParams) {
//                (mDataBinding?.rvSearchProductList?.layoutParams as ViewGroup.MarginLayoutParams).setMargins(SizeUtils.dp2px(7f), SizeUtils.dp2px(10f), SizeUtils.dp2px(7f), 0)
                (mDataBinding?.rvSearchProductList?.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, SizeUtils.dp2px(10f), 0, 0)
            }
        }
        mDataBinding.rvSearchProductList.adapter = mProductListAdapter
        mProductListAdapter?.setOnItemClickListener(this)
    }

    /**
     * 1、推荐 2、销量 3、价格 4、返现
     */
    private fun initFilterView() {
        val item1 = FilterInfoBean("精选", FilterTabConfig.FILTER_TYPE_NO_POP, null, 1)
        val item2 = if (mGoodsSource == GoodsSource.SELF) {
            FilterInfoBean("销量", FilterTabConfig.FILTER_TYPE_NO_POP, null, 2)
        } else {
            if (mGoodsSource == GoodsSource.TAO_BAO_AND_T_MALL) { //淘宝不显示返现
                null
            } else {
                FilterInfoBean("返现", FilterTabConfig.FILTER_TYPE_NO_POP, null, 4)
            }
        }
        val item3 = FilterInfoBean("价格", FilterTabConfig.FILTER_TYPE_NO_POP_HAS_ARROW, null, 3)
        val item4 = FilterInfoBean("筛选", FilterTabConfig.FILTER_TYPE_SHOW_DIALOG, null, FilterTabConfig.FILTER_ITEM_NONE)
        mDataBinding.filterView.addFilterItems(item1, item2, item3, item4)
        mDataBinding.filterView.setOnSelectResultListener(this)
        mDataBinding.filterView.setClickFilter(0)
    }

    override fun initData() {
        super.initData()
        search()
    }

    /**
     * 搜索
     */
    fun search(isRefresh: Boolean = true) {
        if (isRefresh) {
            mProductListAdapter?.data?.clear()
            mDataBinding.viewPageLoad.showPlaceholderView()
        }
        mViewModel.search(getRequestParams(isRefresh), mDataBinding.baseRefreshLayout, mDataBinding.viewPageLoad)
    }

    private fun getRequestParams(isRefresh: Boolean): HashMap<String, String> {
        val params = hashMapOf<String, String>()
        if (isRefresh) mViewModel.mPage = 1
        params["search_item"] = mKeyword
        params["search_type"] = mGoodsSource.type
        params["page"] = mViewModel.mPage.toString()
        params["page_size"] = Constants.Common.PAGE_SIZE.toString()
        if (filterParams.isNotEmpty()) {
            params.putAll(filterParams)
        }
        return params
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            com.baozhun.mall.common.R.id.filter_iv_close -> {
                if (filterParams.isEmpty()) {
                    mDataBinding.filterView.resetSelectData(mDataBinding.filterView.currentIndex, FilterTabConfig.FILTER_TYPE_SHOW_DIALOG)
                }
                filterView?.dismiss()
            }

            com.baozhun.mall.common.R.id.done -> {
                filterParams = filterView?.getResult()!!
                if (filterParams.isEmpty()) {
                    mDataBinding.filterView.resetSelectData(mDataBinding.filterView.currentIndex, FilterTabConfig.FILTER_TYPE_SHOW_DIALOG)
                }
                filterView?.dismiss()
                search(true)
            }

            com.baozhun.mall.common.R.id.reset -> {
                filterParams = hashMapOf()
                mDataBinding.filterView.resetSelectData(mDataBinding.filterView.currentIndex, FilterTabConfig.FILTER_TYPE_SHOW_DIALOG)
                filterView?.dismiss()
                search(true)
            }
        }
    }

    override fun createObserver() {
        mViewModel.mGoodsList.observe(this) {
            mDataBinding.viewPageLoad.hidePlaceholderView()
            loadListData(it, mProductListAdapter, mDataBinding.baseRefreshLayout)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage<Any>) {
        if (event.eventCode == EventCode.BROWSE_GET_POINT_SUCCESS) {
            mProductListAdapter?.data?.find { it.goods_id == event.data.toString() }?.is_get_point = true
            mProductListAdapter?.notifyDataSetChanged()
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        search(true)
    }

    override fun onLoadMore() {
        search(false)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        var goodsInfo = mProductListAdapter?.data?.get(position)
        GoodsDetailActivity.start(mActivity, goodsInfo?.goods_id, goodsInfo?.source.toString())
    }


    override fun onSelectResult(resultBean: FilterResultBean?) {
        if (resultBean?.popupType == FilterTabConfig.FILTER_TYPE_SHOW_DIALOG) {
            filterView = CustomFilterDialog(mActivity, mViewModel.mGoodsList?.value?.getFilterItem(ApiPagerResponse.FILTER_TYPE_ALL), filterParams)
            filterView?.setOnClickCallback(this)
            filterView?.show()
        } else {
            filterParams["sort"] = resultBean?.itemId.toString() // 1、推荐 2、销量 3、价格 4、返现
            if (resultBean?.itemId == 3) {
                filterParams["sort_order"] = if (resultBean?.isArrowUp == true) "1" else "2" // 1-升序，2-降序
            }
            search(true)
        }

    }

    override fun onSelectResultList(resultBeans: MutableList<FilterResultBean>?) {
    }

    override fun useFragmentViewModelStoreOwner(): Boolean {
        return true
    }


    /**
     * 更新关键字
     */
    fun updateKeyWord(keyword: String) {
        mKeyword = keyword
    }


}